/**
 * 
 */
package com.lu.persistence.shiro;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.lu.dto.TaskDto;
import com.lu.model.MyPrincipal;

/**
 * 
 * 自定义的过滤器
 * 
 * @author lusm
 *
 * @Date 2016年4月24日
 */
public class MyFilter extends AccessControlFilter {

	private Logger logger = Logger.getLogger(MyFilter.class);
	private String unauthorizedUrl = "/account/login.html";

	/**
	 * 当前的url与该用户存储在数据库的urls有一个匹配就是有权限
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		MyPrincipal principal = (MyPrincipal) subject.getPrincipal();
		List<TaskDto> tasks = principal.getTasks();
		if (CollectionUtils.isNotEmpty(tasks)) {
			for (TaskDto taskDto : tasks) {
				if (pathsMatch(taskDto.getUrl(), request)) {
					logger.debug("匹配权先中");
					logger.debug("url" + taskDto.getUrl());
					return true;
				}
			}
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.web.filter.AccessControlFilter#onAccessDenied(javax.
	 * servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
			saveRequestAndRedirectToLogin(request, response);
		} else {
			if (StringUtils.hasText(unauthorizedUrl)) {// 如果有未授权页面跳转过去
				WebUtils.issueRedirect(request, response, unauthorizedUrl);
			} else {// 否则返回401未授权状态码
				WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			}
		}
		return false;
	}

}
